Let's draw some maps. 🗺🧐
Let's start with altair. When your dataset is large, it is nice to enable a json data transformer. What it does is, instead of generating and holding the whole dataset in the memory, transform the dataset and save into a temporary file. This makes the whole plotting process much more efficient. For more information, check out: https://altair-viz.github.io/user_guide/data_transformers.html
import altair as alt
# saving data into a file rather than embedding into the chart
alt.data_transformers.enable('json')
#alt.renderers.enable('notebook')
# alt.renderers.enable('jupyterlab')
alt.renderers.enable('default')
Maybe we need a dataset with geographical coordinates. This zipcodes dataset contains the location and zipcode of each zip code area.
from vega_datasets import data
zipcodes_url = data.zipcodes.url
zipcodes = data.zipcodes()
zipcodes.head()
zipcodes.shape
zipcodes = data.zipcodes(dtype={'zip_code': 'category'})
zipcodes.head()
zipcodes.dtypes
zipcodes.zip_code.dtype
zipcodes.county.dtype
Btw, you'll have fewer issues if you pass URL instead of a dataframe to alt.Chart.
Now we have the dataset loaded and start drawing some plots. Let's say you don't know anything about map projections. What would you try with geographical data? Probably the simplest way is considering (longitude, latitude) as a Cartesian coordinate and directly plot them.
alt.Chart(zipcodes_url).mark_circle().encode(
x='longitude:Q',
y='latitude:Q',
)
Actually this itself is a map projection called Equirectangular projection. This projection (or almost a non-projection) is super straight-forward and doesn't require any processing of the data. So, often it is used to just quickly explore geographical data. As you dig deeper, you still want to think about which map projection fits your need best. Don't just use equirectangular projection without any thoughts!
Anyway, let's make it look slighly better by reducing the size of the circles and adjusting the aspect ratio.
Q: Can you adjust the circle size, width and height of the chart?
alt.Chart(zipcodes_url).mark_circle(size=3).encode(
x='longitude:Q',
y='latitude:Q',
).properties(
width=700,
height=200
)
But, a much better way to do this is explicitly specifying that they are lat, lng coordinates by using longitude= and latitude=, rather than x= and y=. If you do that, altair automatically adjust the aspect ratio.
Q: Can you try it?
alt.Chart(zipcodes_url).mark_circle(size=3).encode(
longitude='longitude:Q',
latitude='latitude:Q',
).properties(
width=800,
height=300
)
Because the American empire is far-reaching and complicated, the information density of this map is very low (although interesting). A common projection for visualizing US data is AlbersUSA, which uses Albers (equal-area) projection. This is a standard projection used in United States Geological Survey and the United States Census Bureau. Albers USA contains a composition of US main land, Alaska, and Hawaii.
To use it, we call project method and specify which variables are longitude and latitude.
Q: use the project method to draw the map in the AlbersUsa projection.
alt.Chart(zipcodes_url).mark_circle(size=3).encode(
longitude='longitude:Q',
latitude='latitude:Q',
tooltip='zip_code:N'
).project(
type='albersUsa'
).properties(
width=700,
height=400
)
Now we're talking. 😎
Let's visualize the large-scale zipcode patterns. We can use the fact that the zipcodes are hierarchically organized. That is, the first digit captures the largest area divisions and the other digits are about smaller geographical divisions.
Altair provides some data transformation functionalities. One of them is extracting a substring from a variable.
from altair.expr import datum, substring
alt.Chart(zipcodes_url).mark_circle(size=2).transform_calculate(
'first_digit', substring(datum.zip_code, 0, 1)
).encode(
longitude='longitude:Q',
latitude='latitude:Q',
color='first_digit:N',
).project(
type='albersUsa'
).properties(
width=700,
height=400,
)
For each row (datum), you obtain the zip_code variable and get the substring (imagine Python list slicing), and then you call the result first_digit. Now, you can use this first_digit variable to color the circles. Also note that we specify first_digit as a nominal variable, not quantitative, to obtain a categorical colormap. But we can also play with it too.
Q: Why don't you extract the first two digits, name it as two_digits, and declare that as a quantitative variable? Any interesting patterns? What does it tell us about the history of US?
from altair.expr import datum, substring
alt.Chart(zipcodes_url).mark_circle(size=2).transform_calculate(
'two_digit', substring(datum.zip_code,0,2)
).encode(
longitude='longitude:Q',
latitude='latitude:Q',
color='two_digit:Q',
).project(
type='albersUsa'
).properties(
width=700,
height=400,
)
Q: also try it with declaring the first two digits as a categorical variable
from altair.expr import datum, substring
alt.Chart(zipcodes_url).mark_circle(size=2).transform_calculate(
'two_digit', substring(datum.zip_code,0,2)
).encode(
longitude='longitude:Q',
latitude='latitude:Q',
color='two_digit:N',
).project(
type='albersUsa'
).properties(
width=700,
height=400,
)
Btw, you can always click "view source" or "open in Vega Editor" to look at the json object that defines this visualization. You can embed this json object on your webpage and easily put up an interactive visualization.
Q: Can you put a tooltip that displays the zipcode when you mouse-over? Example https://altair-viz.github.io/gallery/scatter_tooltips.html
from altair.expr import datum, substring
alt.Chart(zipcodes_url).mark_circle(size=2).transform_calculate(
'first_digit', substring(datum.zip_code,0,1)
).encode(
longitude='longitude:Q',
latitude='latitude:Q',
color='first_digit:N',
tooltip='zip_code:N'
).project(
type='albersUsa'
).properties(
width=700,
height=400,
)
from altair.expr import datum, substring
alt.Chart(zipcodes_url).mark_circle(size=2).transform_calculate(
'two_digit', substring(datum.zip_code,0,2)
).encode(
longitude='longitude:Q',
latitude='latitude:Q',
color='two_digit:N',
tooltip='zip_code:N'
).project(
type='albersUsa'
).properties(
width=700,
height=400,
)
Let's try some choropleth now. Vega datasets have US county / state boundary data (us_10m) and world country boundary data (world-110m). You can take a look at the boundaries on GitHub (they renders topoJSON files):
If you click "Raw" then you can take a look at the actual file, which is hard to read.
Essentially, each file is a large dictionary with the following keys.
usmap = data.us_10m()
usmap.keys()
usmap['type']
usmap['transform']
This transformation is used to quantize the data and store the coordinates in integer (easier to store than float type numbers).
https://github.com/topojson/topojson-specification#212-transforms
usmap['objects'].keys()
This data contains not only county-level boundaries (objects) but also states and land boundaries.
usmap['objects']['land']['type'], usmap['objects']['states']['type'], usmap['objects']['counties']['type']
land is a multipolygon (one object) and states and counties contains many geometrics (multipolygons) because there are many states (counties). We can look at a state as a set of arcs that define it. It's id captures the identity of the state and is the key to link to other datasets.
state1 = usmap['objects']['states']['geometries'][1]
state1
The arcs referred here is defined in usmap['arcs'].
usmap['arcs'][:10]
It seems pretty daunting to work with this dataset, right? But fortunately people have already built tools to handle such data.
# states
states = alt.topo_feature(data.us_10m.url, 'states')
# us counties
us_counties = alt.topo_feature(data.us_10m.url, 'counties')
states
Q. Can you find a mark for geographical shapes from here https://altair-viz.github.io/user_guide/marks.html and draw the states?
alt.Chart(states).mark_geoshape(
stroke='white',
strokeWidth=0.1).properties(
width=500,
height=300
)
And then project it using the albersUsa?
alt.Chart(states).mark_geoshape(
stroke='white',
strokeWidth=0.1).project(
type='albersUsa'
).properties(
width=500,
height=300
)
Can you do the same thing with counties and draw county boundaries? (hint: you have to use alt.topo_feature())
states = alt.Chart(states).mark_geoshape(
stroke='white',
strokeWidth=0.1).project(
type='albersUsa'
).properties(
width=500,
height=300
)
counties = alt.Chart(us_counties).mark_geoshape(
stroke='white',
strokeWidth=0.1
).project('albersUsa')
states + counties
Let's load some county-level unemployment data.
unemp_data = data.unemployment(sep='\t')
unemp_data.head()
This dataset has unemployment rate. When? I don't know. We don't care about data provenance here because the goal is quickly trying out choropleth. But if you're working with a real dataset, you should be very sensitive about the provenance of your dataset. Make sure you understand where the data came from and how it was processed.
Anyway, for each county specified with id. To combine two datasets, we use "Lookup transform" - https://vega.github.io/vega/docs/transforms/lookup/. Essentially, we use the id in the map data to look up (again) id field in the unemp_data and then bring in the rate variable. Then, we can use that rate variable to encode the color of the geoshape mark.
alt.Chart(us_counties).mark_geoshape().project(
type='albersUsa'
).transform_lookup(
lookup='id',
from_=alt.LookupData(data.unemployment.url, 'id', ['rate'])
).encode(
color='rate:Q'
).properties(
width=700,
height=400
)
There you have it, a nice choropleth map. 😎
Although many geovisualizations use vector graphics, raster visualization is still useful especially when you deal with images and lots of datapoints. Datashader is a package that aggregates and visualizes a large amount of data very quickly. Given a scene (visualization boundary, resolution, etc.), it quickly aggregate the data and produce pixels and send them to you.
To appreciate its power, we need a fairly large dataset. Let's use NYC taxi trip dataset on Kaggle: https://www.kaggle.com/kentonnlp/2014-new-york-city-taxi-trips You can download even bigger trip data from NYC open data website: https://opendata.cityofnewyork.us/data/
Ah, and you want to install the datashader, bokeh, and holoviews first if you don't have them yet. If you have them make sure they are the latest version
pip install -U datashader bokeh holoviews
or
conda install datashader bokeh holoviews
!pip install -U datashader bokeh holoviews
%matplotlib inline
import pandas as pd
import datashader as ds
from datashader import transfer_functions as tf
from colorcet import fire
Because the dataset is pretty big, let's use a small sample first. For this visualization, we only keep the dropoff location.
Usually, we use remotezip package in Python to download and extract the big dataset. But one of the problem with remotezip is that it does not support range request and that is why we have to download the dataset manually. We suggest you to download the zip file of dataset containing csv from Kaggle dataset, extract it and put the filepath of CSV file in the csv_path variable below.
from google.colab import drive
drive.mount('/content/drive')
dirpath = '/content/drive/MyDrive/Data/data_Viz/'
# dirpath = '/content/drive/MyDrive/Data/'
!ls $dirpath
csv_path= dirpath + 'nyc_taxi_data_2014.csv'
try:
nyctaxi_small = pd.read_csv(csv_path, nrows=10000,
usecols=['dropoff_longitude', 'dropoff_latitude'])
except:
print("Dataset URL is not correct or not defined:")
print("Creating dummy dataset so that code won't break but for assignment, you must use actual dataset.")
# nyctaxi_small = pd.DataFrame({"dropoff_longitude": [-73, -74], "dropoff_latitude": [40, 41]})
nyctaxi_small.head()
Although the dataset is different, we can still follow the example here: https://datashader.org/getting_started/Introduction.html
agg = ds.Canvas().points(nyctaxi_small, 'dropoff_longitude', 'dropoff_latitude')
tf.set_background(tf.shade(agg, cmap=fire),"black")
Why can't we see anything? Wait, do you see the small dots on the left top? Can that be New York City? Maybe we don't see anything because some people travel very far? or because the dataset has some missing data?
Q: Can you first check whether there are NaNs? Then drop them and draw the map again?
# Implement: Check whether we have NaNs
nyctaxi_small.isna().sum()
# Implement: drop the rows with NaN and then draw the map again.
nyctaxi_small = nyctaxi_small.dropna(axis=0)
nyctaxi_small.isna().sum()
agg = ds.Canvas().points(nyctaxi_small, 'dropoff_longitude', 'dropoff_latitude')
tf.set_background(tf.shade(agg, cmap=fire),"black")
So it's not about the missing data.
Q: Can you identify the issue and draw the map like the following?
hint: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.between.html and histograms may be helpful.
# nyctaxi_small.describe()
# nyctaxi_small.info()
import matplotlib.pyplot as plt
# nyctaxi_small.plot.hist()
plt.hist(nyctaxi_small.dropoff_longitude)
plt.hist(nyctaxi_small.dropoff_latitude)
nyctaxi_small[nyctaxi_small['dropoff_longitude']==0].shape
New York/Coordinates 40.7128° N, 74.0060° W
https://www.kaggle.com/code/muhammedazamkhan/interactive-data-visualization-nyc-taxi-trip/notebook
(-74.05, -73.7), (40.6, 40.9)
# nyctaxi_small_filtered = nyctaxi_small[nyctaxi_small['dropoff_longitude'].between(-74.05, -73.7) ]
# nyctaxi_small_filtered = nyctaxi_small_filtered[nyctaxi_small_filtered['dropoff_latitude'].between(40.6, 40.9)]
# Implement. You can use multiple cells to figure out what's going on.
# TODO: Once you figure it out, Replace below dummy value of df nyctaxi_small_filtered with correct value where the issue is resolved
nyctaxi_small_filtered = nyctaxi_small[nyctaxi_small['dropoff_longitude'].between(-74.1, -73.7) ]
nyctaxi_small_filtered = nyctaxi_small_filtered[nyctaxi_small_filtered['dropoff_latitude'].between(40, 40.9)]
agg = ds.Canvas().points(nyctaxi_small_filtered, 'dropoff_longitude', 'dropoff_latitude')
tf.set_background(tf.shade(agg, cmap=fire), "black")
agg = ds.Canvas().points(nyctaxi_small_filtered, 'dropoff_longitude', 'dropoff_latitude')
tf.set_background(tf.shade(agg, cmap=fire), "black")
Do you see the black empty space at the center? That looks like the Central Park. This is cool, but it'll be awesome if we can explore the data interactively.
Q. Ok, now let's get serious by loading the whole dataset. It may take some time. Apply the same data cleaning procedure.
%%time
# Implement
nyctaxi_small = pd.read_csv(csv_path, usecols=['dropoff_longitude', 'dropoff_latitude'])
Can you feed the data directly to datashader to reproduce the static plot, this time with the full data?
# %%time
nyctaxi_small_filtered = nyctaxi_small[nyctaxi_small['dropoff_longitude'].between(-74.1, -73.7) ]
nyctaxi_small_filtered = nyctaxi_small_filtered[nyctaxi_small_filtered['dropoff_latitude'].between(40.5, 41)]
agg = ds.Canvas().points(nyctaxi_small_filtered, 'dropoff_longitude', 'dropoff_latitude')
tf.set_background(tf.shade(agg, cmap=fire), "black")
Wow, that's fast. Also it looks cool!
Let's try the interactive version from here: https://datashader.org/getting_started/Introduction.html
nyctaxi_small.shape , nyctaxi_small_filtered.shape
import holoviews as hv
from holoviews.element.tiles import EsriImagery
from holoviews.operation.datashader import datashade
hv.extension('bokeh')
map_tiles = EsriImagery().opts(alpha=0.5, width=900, height=480, bgcolor='black')
points = hv.Points(nyctaxi_small_filtered, ['dropoff_longitude', 'dropoff_latitude'])
taxi_trips = datashade(points, x_sampling=1, y_sampling=1, cmap=fire, width=900, height=480)
map_tiles * taxi_trips
Why does it say "map data not yet available"? The reason is the difference between two coordinate systems. If you google this error message, you can find https://stackoverflow.com/questions/44487898/map-background-with-datashader-map-data-not-yet-available.
You can use datashader.utils.lnglat_to_meters to convert your latitudes and longitudes to a format that holoviews understands. More on this here: https://datashader.org/user_guide/Geography.html
Q: Can you draw an interactive map by converting the lnglat data to x, y coordinate explained above?
nyctaxi_small_filtered.head()
%%time
nyctaxi_small_mercator = pd.DataFrame(ds.utils.lnglat_to_meters(nyctaxi_small_filtered['dropoff_longitude'], nyctaxi_small_filtered['dropoff_latitude']))
nyctaxi_small_mercator = nyctaxi_small_mercator.T
nyctaxi_small_mercator.head()
# https://stackoverflow.com/questions/44487898/map-background-with-datashader-map-data-not-yet-available
# https://github.com/holoviz/datashader/blob/master/datashader/utils.py
# datashader.utils.lnglat_to_meters()
# import holoviews as hv
# from holoviews.element.tiles import EsriImagery
# from holoviews.operation.datashader import datashade
hv.extension('bokeh')
map_tiles = EsriImagery().opts(alpha=0.5, width=900, height=480, bgcolor='black')
points = hv.Points(nyctaxi_small_mercator, ['dropoff_longitude', 'dropoff_latitude'])
taxi_trips = datashade(points, x_sampling=1, y_sampling=1, cmap=fire, width=900, height=480)
map_tiles * taxi_trips
# Implement
It's interactive! Actually, if you are running a bokeh server and there is a live python process, the map quickly refreshes and show more details as you zoom.
Q: how many rows (data points) are we visualizing right now?
# figure it out
nyctaxi_small_mercator.shape
We are visualizing 14751421 data points
That's a lot of data points. If we are using a vector format, it is probably hopeless to expect any interactivity because you need to move that many points! Yet, datashader + holoviews + bokeh renders everything almost in real time!
Another useful tool is Leaflet. It allows you to use various map tile data (Google maps, Open streetmap, ...) with many types of marks (points, heatmap, etc.). Leaflet.js is one of the easiest options to do that on the web, and there is a Python bridge of it: https://github.com/jupyter-widgets/ipyleaflet. Although we will not go into details, it's certainly something that's worth checking out if you're using geographical data.
# %%shell
# jupyter nbconvert --to html /content/m12_lab_Ganapathy_Anitha.ipynb